package org.sifebint.backend.dao.reports;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.sifebint.backend.model.Report;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

public class ReportDaoImpl extends SimpleJdbcDaoSupport implements ReportDao {
  
  private String queryCreateReport;
  
  private String queryDeleteReport;
  
  private String queryMoveReport;
  
  private String queryUpdateReport;
  
  private String queryLoadReport;
  
  @Override
  public Report loadReport(long reportId) {
    return getSimpleJdbcTemplate().queryForObject(
        queryLoadReport, 
        new ParameterizedRowMapper<Report>() {
          @Override
          public Report mapRow(ResultSet rs, int rowNum) throws SQLException {
            Report report = new Report();
            report.setId(rs.getLong("id"));
            report.setDataSourceId(rs.getLong("data_source_id"));
            report.setName(rs.getString("name"));
            report.setSql(rs.getString("sql_string"));
            return report;
          }
        },
        new Object[] { reportId });
  }
  
  @Override
  public void createReport(long folderId, Report report) {
    getSimpleJdbcTemplate().update(
        queryCreateReport, 
        new Object[] { 
            report.getName(),
            report.getSql(),
            report.getDataSourceId(),
            folderId});
  }

  @Override
  public void deleteReport(long reportId) {
    getSimpleJdbcTemplate().update(queryDeleteReport, new Object[] { reportId });

  }

  @Override
  public void moveReport(long reportId, long destinationFolderId) {
    getSimpleJdbcTemplate().update(queryMoveReport, new Object[] { destinationFolderId, reportId });
  }

  @Override
  public void updateReport(Report report) {
    getSimpleJdbcTemplate().update(queryUpdateReport, 
        new Object[] {
          report.getName(),
          report.getSql(),
          report.getDataSourceId(),
          report.getId()
        });
  }
  
  @Required
  public void setQueryCreateReport(String queryCreateReport) {
    this.queryCreateReport = queryCreateReport;
  }
  
  @Required
  public void setQueryDeleteReport(String queryDeleteReport) {
    this.queryDeleteReport = queryDeleteReport;
  }
  
  @Required
  public void setQueryMoveReport(String queryMoveReport) {
    this.queryMoveReport = queryMoveReport;
  }
  
  @Required
  public void setQueryLoadReport(String queryLoadReport) {
    this.queryLoadReport = queryLoadReport;
  }
  
  @Required
  public void setQueryUpdateReport(String queryUpdateReport) {
    this.queryUpdateReport = queryUpdateReport;
  }
  
}
